package com.huwei.modules.base.util;

public class CodingUtil {

	/**
	 * 创建给定父编码的下一个孩子编码 ，父编码为空或空串，等同于创建起始编码
	 * @param parentCode 父编码
	 * @param allLength 编码整体长度
	 * @param nodeLength 每一个节点编码的长度
	 * @return
	 */
	static public String createChildCascadeCoding(String parentCode ,int allLength ,int nodeLength) {
		parentCode = parentCode == null ? "" : StringUtil.delSuffix(parentCode, "0");
		if(parentCode.length() + nodeLength > allLength) {
			throw new RuntimeException("StringUtil#createChildCascadeCoding error ,cause: result length  " + (parentCode.length() + nodeLength) +"gt allLength " + allLength);
		}
		return StringUtil.addSuffix(
				new StringBuffer().append(parentCode).append(StringUtil.addSuffix("", "0", nodeLength -1)).append("1").toString()
				, "0", allLength);
	}
	
	/**
	 * 	创建给定兄弟编码的下一个编码 ，兄弟编码为空或空串，等同于创建起始编码
	 * @param brotherCode兄弟编码
	 * @param allLength 编码整体长度
	 * @param nodeLength 每一个节点编码的长度
	 * @return
	 */
	static public String createBrotherCascadeCoding(String brotherCode ,int allLength ,int nodeLength) {
		brotherCode = brotherCode == null ? "" : brotherCode;
		String temp = StringUtil.delSuffix(brotherCode, "0");
		String parentCode = temp.length() >= nodeLength ? temp.substring(0,temp.length() - nodeLength) : "";
		String brotherNumber = temp.length() >= nodeLength ? temp.substring(temp.length() - nodeLength) : "0";
		//兄弟编码
		long brotherN = 0;
		try {
			brotherN = Long.parseLong(brotherNumber); 
		}catch (Exception e) {
			throw new RuntimeException("StringUtil#createBrotherCascadeCoding error ,cause : brotherCode error : " + brotherCode);
		}
		//当前编码
		String cNumber = String.valueOf(++brotherN);
		if(cNumber.length() > nodeLength) {
			throw new RuntimeException("StringUtil#createBrotherCascadeCoding error ,cause : next brother code transgression ,brotherCode:" + brotherCode + " ;next code:" + brotherNumber );
		}
		//组合父级编码
		String cCode = parentCode + StringUtil.addPrefix(cNumber, "0", nodeLength);
		return StringUtil.addSuffix(cCode, "0", allLength);
	}
	
//	static public void main(String[] args) {
//		System.out.println(createChildCascadeCoding("00001000000000000000", 20, 5));
//		
//		System.out.println(createBrotherCascadeCoding("001010202", 20, 2));
//		
//	}
}
